import re
import os
if os.system('dd if=/dev/zero of=gen_fs.img bs=1M count=2') != 0: exit(-1)
if os.system ('mkfs.fat -v -F 12 -S 512 -s 1 gen_fs.img > gen_fsimginfo') !=0 : exit(-1)
os.system('file gen_fs.img')
info = open("gen_fsimginfo" ,"r")

patterns = {
    'BPB_NnuHeads': r".* has (\d+) heads",
    'BPB_SecPerTrk': r".* (\d+) sectors per track",
    'BPB_BytesPerSec': r".*logical sector size is (\d+)",
    'BPB_Media': r".*using (0[xX][0-9a-fA-F]+) media descriptor",
    'BPB_TotSec16': r".*with (\d+) sectors",
    'BS_DrvNum': r".*drive number (0[xX][0-9a-fA-F]+)",
    'BPB_NumFATs': r".* (\d+) 12-bit FATs",
    'BPB_SecPerClus': r".* (\d+) sector per cluster",
    'BPB_FATSz16': r".*FAT size is (\d+) sectors",
    'BPB_RsvdSecCnt': r".*There is (\d+) reserved sector",
    'BPB_RootEntCnt': r".*Root directory contains (\d+) slots",
    'BPB_RootDirSectors': r".*Root directory contains \d+ slots and uses (\d+) sectors"
}
"""
this code assert(BS_DrvNum==0x80)
"""
output = open("gen_step2_1.asm","w")
for line in info.readlines():
    for k,v in patterns.items():
        match = re.match(patterns[k],line)
        if match:(print(k,":",match.group(1)),output.write(f"{k:20}equ{match.group(1):>10}\n"))

output.write("SectorNumOfRootDirStart      equ      BPB_RsvdSecCnt + ( BPB_NumFATs * BPB_FATSz16 )\n")
output.write("SectorNumOfFATlStart         equ      BPB_RsvdSecCnt\n")
output.write("SectorNumOfDataStart         equ      SectorNumOfRootDirStart + BPB_RootDirSectors\n")
output.write("RootEntCntPerSec             equ      BPB_RootEntCnt / BPB_RootDirSectors\n")
output.write("""
             
;Given any valid data cluster number N, the sector number of the first sector of that cluster is 
;computed as follows: 
;FirstSectorofCluster = ((N - 2) * BPB_SecPerClus) + FirstDataSector;
             
             """)
output.close()
info.close()